package com.mmy.fta.cargo.web.rest;

import com.mmy.fta.cargo.api.model.CargoFeature;
import com.mmy.fta.cargo.web.request.PrePriceRequest;
import com.mmy.fta.cargo.server.dto.ShipperCargoDTO;
import com.mmy.fta.cargo.server.entity.CargoInfoEntity;
import com.mmy.fta.cargo.server.service.ComputeDistanceMeter;
import com.mmy.fta.cargo.server.service.PublishCargoInfoService;
import com.mmy.fta.cargo.web.enums.DefaultResponseCode;
import com.mmy.fta.cargo.web.request.PublishCargoRequest;
import com.mmy.fta.cargo.web.response.PrePriceResponse;
import com.mmy.fta.cargo.web.response.PublishCargoResponse;
import com.mmy.fta.cargo.web.util.SnowflakeIdUtils;
import com.mmy.fta.coldtruck.api.ColdTruckService;
import com.mmy.fta.coldtruck.api.dto.ColdTruckDTO;
import com.mmy.fta.usercenter.api.CargoTimesDeductService;
import com.mmy.fta.usercenter.api.UserService;
import com.ymm.common.rpc.YmmResult;
//import io.manbang.ironman.api.idempotent.annotation.Idempotent;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @author guohao.xie
 * @apiNote
 * @exportable
 * @since 2021/10/20
 */
@Slf4j
@RestController
@RequestMapping(value = "/publish")
public class PublishCargoController {

    @Autowired
    PublishCargoInfoService publishCargoInfoService;
    @Autowired
    ComputeDistanceMeter computeDistanceMeter;

    @Reference
    CargoTimesDeductService cargoTimesDeductService;

    @Reference
    ColdTruckService coldTruckService;

    @Reference
    UserService userService;

    // todo mi deng
    /**
     * 货主发布货源
     */
    @PostMapping(value = "publishCargo")
    public YmmResult<PublishCargoResponse> getPulishCargo(@RequestBody PublishCargoRequest publishCargoRequest) {
        long start = System.currentTimeMillis();

        PublishCargoResponse response = new PublishCargoResponse();
        log.info("货主发货请求：{}",publishCargoRequest.toString());
        if(Objects.isNull(publishCargoRequest.getOpenId())){
            response.setErrorMsg("请求参数不全");
            response.respond(DefaultResponseCode.PARAMS_ERROR);
            response.setResult(0);
            return YmmResult.succResult(response);
        }
        try {
            if (null == publishCargoRequest) {
                response.setErrorMsg(DefaultResponseCode.PARAMS_ERROR.getMsg());
                response.respond(DefaultResponseCode.PARAMS_ERROR);
                response.setResult(0);
                return YmmResult.succResult(response);
            }
            //查询剩余发货次数和货主id
            ShipperCargoDTO shipperCargoDTO = new ShipperCargoDTO();
            shipperCargoDTO = publishCargoInfoService.sendCargoMsg(publishCargoRequest.getOpenId());

            if (Objects.equals(shipperCargoDTO.getRemianDeliverys(), 0)) {
                response = new PublishCargoResponse();
                response.respond(DefaultResponseCode.REMIAN_DELIVERYS);
                response.setResult(0);
                return YmmResult.succResult(response);
            }

            CargoInfoEntity cargoInfoEntity = new CargoInfoEntity();
            BeanUtils.copyProperties(publishCargoRequest, cargoInfoEntity);
            //shipper-idno
            cargoInfoEntity.setShipperIdNo(shipperCargoDTO.getIdentityNo());

            //雪花算法生成货源id
            SnowflakeIdUtils idWorker = new SnowflakeIdUtils(3, 1);
            String cargoId = String.valueOf(idWorker.nextId());
            cargoInfoEntity.setCargoId(cargoId);

            //计算公里数
            double meter1 = computeDistanceMeter.getDistanceMeter(
                    new GlobalCoordinates(Double.parseDouble(publishCargoRequest.getLoadLatitude()), Double.parseDouble(publishCargoRequest.getLoadLongitude())),
                    new GlobalCoordinates(Double.parseDouble(publishCargoRequest.getUnloadLatitude()), Double.parseDouble(publishCargoRequest.getUnloadLongitude())),
                    Ellipsoid.Sphere);
            cargoInfoEntity.setMileage(meter1);
            cargoInfoEntity.setCargoStatus(10);

            //计算抽佣
            CargoFeature cargoFeature = new CargoFeature();
            cargoFeature.setCargoCapacity(publishCargoRequest.getCargoCapacipy());
            cargoFeature.setCargoFreight(publishCargoRequest.getCargoFee());
            cargoFeature.setCargoWeight(publishCargoRequest.getTruckWeight());
            cargoFeature.setLoadHhour(publishCargoRequest.getLoadTime());
            cargoFeature.setTruckLength(publishCargoRequest.getTruckLength());
            cargoFeature.setTruckType(publishCargoRequest.getTruckType());
            cargoFeature.setSecondCategory(publishCargoRequest.getCargoName());
            cargoFeature.setStartLat(publishCargoRequest.getLoadLatitude());
            cargoFeature.setStartLon(publishCargoRequest.getLoadLongitude());
            cargoFeature.setEndLat(publishCargoRequest.getUnloadLatitude());
            cargoFeature.setEndLon(publishCargoRequest.getUnloadLongitude());
            cargoFeature.setIsReturnDeposit(publishCargoRequest.getNeedReturnDeposit());
            cargoFeature.setDepositAmt(publishCargoRequest.getDeposit());

            try {
                int autoCommissionPrice = publishCargoInfoService.autoCommission(cargoFeature);
                cargoInfoEntity.setEstimateDistance(autoCommissionPrice);
            }catch(Exception e){
                log.info(e.toString());
                cargoInfoEntity.setEstimateDistance(0);
            }

            if(Objects.isNull(cargoInfoEntity.getEstimateDistance())){
                cargoInfoEntity.setEstimateDistance(0);
            }

            //冷藏
            if(Objects.equals(publishCargoRequest.getTruckType(),"冷藏车") ){
                cargoInfoEntity.setBuyoutPrice(true);

                // 冷链货主 发冷链
                if(userService.queryShipperIsColdMember(publishCargoRequest.getOpenId())){
                    ColdTruckDTO coldTruckDTO = new ColdTruckDTO();

                    coldTruckDTO.setCargoId(cargoId);

                    coldTruckDTO.setTemperature(publishCargoRequest.getTemperature());
                    coldTruckDTO.setHumidity(publishCargoRequest.getHumidity());

                    String[] loadProvinceTemp = publishCargoRequest.getLoadAddress().split("-");
                    String loadProvince = loadProvinceTemp[0];
                    String loadCity = loadProvinceTemp[1];

                    coldTruckDTO.setLoadProvince(loadProvince);
                    coldTruckDTO.setLoadCity(loadCity);
                    coldTruckDTO.setContactLoadAddress(loadProvince+loadCity);

                    String[] unloadProvinceTemp = publishCargoRequest.getUnloadingAdress().split("-");
                    String unloadProvince = unloadProvinceTemp[0];
                    String unloadCity = unloadProvinceTemp[1];

                    coldTruckDTO.setUnloadProvince(unloadProvince);
                    coldTruckDTO.setUnloadCity(unloadCity);
                    coldTruckDTO.setContactUnloadAddress(unloadProvince+unloadCity);

                    try {
                        coldTruckService.publishColdCargo(coldTruckDTO);
                    }catch (Exception e){
                        log.info(e.toString());
                    }

                    cargoInfoEntity.setStandardCargo(true);
                }

            }else {
                cargoInfoEntity.setBuyoutPrice(false);
            }

            int result = publishCargoInfoService.insertPublishResult(cargoInfoEntity);
            if (Objects.equals(result, 0)) {
                response.setResult(0);
                return YmmResult.succResult(response);
            }
            //发货成功后扣减发货次数
            int cargoTimes=cargoTimesDeductService.cargoTimesDeductService(publishCargoRequest.getOpenId());
            //发货成功后增加已发次数
            int sendTimes=cargoTimesDeductService.sendTimesAddService(publishCargoRequest.getOpenId());

            response.setResult(1);
            log.info("货主发货成功，发货次数减一");
            long end = System.currentTimeMillis();

            log.info("publish-time:{}",end-start);

            return YmmResult.succResult(response);
        } catch (Exception e) {
            response.setErrorMsg(e.getMessage());
            response.setResult(0);
            return YmmResult.succResult(response);
        }
    }

    /**
     * 算法定价
     */
    @PostMapping(value = "getPrePrice")
    public PrePriceResponse getPrePrice(@RequestBody PrePriceRequest prePriceRequest) {
        PrePriceResponse prePriceResponse = new PrePriceResponse();

        CargoFeature cargoFeature = new CargoFeature();
        BeanUtils.copyProperties(prePriceRequest, cargoFeature);
        Integer price= publishCargoInfoService.autoPrice(cargoFeature);
        log.info("返回定价：{}",price);

        prePriceResponse.setPrice(price);
        String phone = publishCargoInfoService.userDefaultPhone(prePriceRequest.getOpenId());
        prePriceResponse.setPhone(phone);
        log.info("返回用户默认电话：{}",phone);

        //雪花算法生成pageId
        SnowflakeIdUtils idWorker = new SnowflakeIdUtils(3, 1);
        String pageId = String.valueOf(idWorker.nextId());
        prePriceResponse.setPageId(pageId);

        return prePriceResponse;
    }

}
